﻿Imports System.Net.NetworkInformation
Imports System.Windows.Forms
Imports System.IO
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraTreeList.Nodes
Imports DevExpress.XtraTreeList
Imports DevExpress.XtraTreeList.Nodes.Operations
Imports System.Text
Imports System.Security.Cryptography

Public Module ModuleMethod
    Public Class TreeListViewState
        Private expanded As ArrayList
        Private selected As ArrayList

        'TreeListNode đang focused
        Private focused As Object

        'Index của TreeListNode trên cùng
        Private topIndex As Integer
        Private treeList_Renamed As TreeList
        Public Property TreeList() As TreeList
            Get
                Return treeList_Renamed
            End Get
            Set(ByVal value As TreeList)
                treeList_Renamed = value
                Clear()
            End Set
        End Property
        Private Class OperationSaveExpanded
            Inherits TreeListOperation
            Private al As ArrayList = New ArrayList()
            Public ReadOnly Property Nodes() As ArrayList
                Get
                    Return al
                End Get
            End Property
            'Lấy về danh sách các giá trị của các node có node con và đang ở trạng thái Expanded
            Public Overrides Sub Execute(ByVal node As TreeListNode)
                If node.HasChildren AndAlso node.Expanded Then
                    al.Add(node.GetValue(node.TreeList.KeyFieldName))
                End If
            End Sub
        End Class

        'Khởi tạo khi không có tham số
        Public Sub New()
            Me.New(Nothing)
        End Sub

        'Khởi tạo với tham số đưa vào
        Public Sub New(ByVal treeList_Renamed As TreeList)
            Me.treeList_Renamed = treeList_Renamed
            expanded = New ArrayList()
            selected = New ArrayList()
        End Sub

        'Xóa các thông số State
        Public Sub Clear()
            expanded.Clear()
            selected.Clear()
            focused = Nothing
            topIndex = 0
        End Sub

        Private Function GetExpanded() As ArrayList
            Dim op As OperationSaveExpanded = New OperationSaveExpanded()
            TreeList.NodesIterator.DoOperation(op)
            Return op.Nodes
        End Function

        Private Function GetSelected() As ArrayList
            Dim al As ArrayList = New ArrayList()
            For Each node As TreeListNode In TreeList.Selection
                al.Add(node.GetValue(TreeList.KeyFieldName))
            Next
            Return al
        End Function

        Public Sub LoadState()
            TreeList.BeginUpdate()
            Try
                TreeList.CollapseAll()
                Dim node As TreeListNode
                For Each key As Object In expanded
                    node = TreeList.FindNodeByKeyID(key)
                    If Not node Is Nothing Then
                        node.Expanded = True
                    End If
                Next
                For Each key As Object In selected
                    node = TreeList.FindNodeByKeyID(key)
                    If Not node Is Nothing Then
                        TreeList.Selection.Add(node)
                    End If
                Next
                TreeList.FocusedNode = TreeList.FindNodeByKeyID(focused)
            Finally
                TreeList.EndUpdate()
                TreeList.TopVisibleNodeIndex = TreeList.GetVisibleIndexByNode(TreeList.FocusedNode) - topIndex
            End Try
        End Sub

        Public Sub SaveState()
            If Not TreeList.FocusedNode Is Nothing Then
                expanded = GetExpanded()
                selected = GetSelected()
                focused = TreeList.FocusedNode(TreeList.KeyFieldName)
                topIndex = TreeList.GetVisibleIndexByNode(TreeList.FocusedNode) - TreeList.TopVisibleNodeIndex
            Else
                Clear()
            End If
        End Sub
    End Class
    Public Function ConvertCollectionToString(ByVal iCollecton As Collection) As String
        Dim iKeyStr As String = ""
        If iCollecton IsNot Nothing Then
            For i As Integer = 1 To iCollecton.Count
                If i = 1 Then
                    iKeyStr = CStr(iCollecton.Item(i))
                Else
                    iKeyStr = iKeyStr & "," & CStr(iCollecton.Item(i))
                End If
            Next
        End If
        ConvertCollectionToString = iKeyStr
    End Function
    ''' <summary>
    ''' Tra ra key code cần thiết
    ''' </summary>
    ''' <param name="keyName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetKeyCode(ByVal keyName As String) As Integer
        Dim KeyCodeReturn As Integer = (From ds In vlstPhimTat _
                                        Where ds.MaNut = keyName Select ds.KeyCode).FirstOrDefault
        Dim KeyFn2 As Integer = (From ds In vlstPhimTat _
                                 Where ds.MaNut = keyName Select ds.KeyFn).FirstOrDefault
        If KeyFn2 <> 0 Then
            Return 0
        Else
            Return KeyCodeReturn
        End If
    End Function
    ''' <summary>
    ''' Tra ra key code cần thiết
    ''' </summary>
    ''' <param name="keyName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetKeyCode2(ByVal keyName As String) As Integer
        Try
            Dim KeyCodeReturn As Integer = (From ds In vlstPhimTat _
                                            Where ds.MaNut = keyName Select ds.KeyCode).FirstOrDefault

            Return KeyCodeReturn
        Catch ex As Exception
            MsgInfo(ex.Message)
        End Try
    End Function

    Public Function GetKeyModifide(ByVal keyName As String) As Integer
        Try
            Dim KeyCodeReturn As Integer = (From ds In vlstPhimTat _
                                            Where ds.MaNut = keyName Select ds.KeyFn).FirstOrDefault
            Return KeyCodeReturn
        Catch ex As Exception
            MsgInfo(ex.Message)
        End Try
    End Function

    ''' <summary>
    ''' Tra ra ki tu key 
    ''' </summary>
    ''' <param name="keyCode"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function KeyCodeToChar(ByVal keyCode As Integer) As String

        Dim key As Keys = keyCode
        Select Case key
            Case Keys.Add
                Return "+"
            Case Keys.Decimal
                Return "."
            Case Keys.Divide
                Return "/"
            Case Keys.Multiply
                Return "*"
            Case Keys.OemBackslash
                Return "\\"
            Case Keys.OemCloseBrackets
                Return "]"
            Case Keys.OemMinus
                Return "-"
            Case Keys.OemOpenBrackets
                Return "["
            Case Keys.OemPeriod
                Return "."
            Case Keys.OemPipe
                Return "|"
            Case Keys.OemQuestion
                Return "/"
            Case Keys.OemQuotes
                Return "\"";"
            Case Keys.OemSemicolon
                Return ";"
            Case Keys.Oemcomma
                Return ","
            Case Keys.Oemplus
                Return "+"
            Case Keys.Oemtilde
                Return "`"
            Case Keys.Separator
                Return "-"
            Case Keys.Subtract
                Return "-"
            Case Keys.D0
                Return "0"
            Case Keys.D1
                Return "1"
            Case Keys.D2
                Return "2"
            Case Keys.D3
                Return "3"
            Case Keys.D4
                Return "4"
            Case Keys.D5
                Return "5"
            Case Keys.D6
                Return "6"
            Case Keys.D7
                Return "7"
            Case Keys.D8
                Return "8"
            Case Keys.D9
                Return "9"
            Case Keys.Space
                Return " "
            Case Else
                Return key.ToString()
        End Select

    End Function

    ''' <summary>
    ''' Tạo ID cho bảng
    ''' </summary>
    ''' <returns>ID mới(string)</returns>
    ''' <remarks></remarks>
    Public Function CreateID() As String
        Try
            'Return String.Format("{0}_{1}_{2}", vBienMoiTruongPH.PH_QL_Server, vUser.CanBo.UserName, System.Guid.NewGuid())
            'Return String.Format("{0}", System.Guid.NewGuid())
            Return String.Format("{0}_{1}", vUser.CanBo.UserName, System.Guid.NewGuid())

        Catch ex As Exception
            Return System.Guid.NewGuid().ToString
        End Try
    End Function

    Public Sub MsgInfo(ByVal strErr As String)
        vMsg.Show(strErr, "QLNH", vMsg.vButtons.vOK, vMsg.vIcon.vInformation)
    End Sub

    Public Sub MsgErr(ByVal strErr As String)
        vMsg.Show(strErr, "QLNH", vMsg.vButtons.vOK, vMsg.vIcon.vError)
    End Sub

    Public Function MsgAskDelete(ByVal strErr As String) As vMsg.vReSult
        Return vMsg.Show(strErr, "QLNH", vMsg.vButtons.vYesNo, vMsg.vIcon.vQuestion, vMsg.vDefaultButtons.vButton2)
    End Function

    Public Function MsgVuotKeHoach(ByVal strErr As String) As vMsg.vReSult
        Return vMsg.Show(strErr, "QLNH", vMsg.vButtons.vYesNo, vMsg.vIcon.vInformation, vMsg.vDefaultButtons.vButton1, True)
    End Function

    Public Function MsgAskSaveData(ByVal strErr As String) As vMsg.vReSult
        Return vMsg.Show(strErr, "QLNH", vMsg.vButtons.vYesNoCancel, vMsg.vIcon.vInformation)
    End Function

    Public Function GetMACAddress() As String
        Dim tmp As String
        Dim Card() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
        tmp = Card(0).GetPhysicalAddress().ToString
        Return tmp
    End Function

    ''' <summary>
    ''' Cập nhật các lệnh Thêm, Sửa, Xóa vào CSDL
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub iSubmitChange()
        Try
            dbTV.SubmitChanges(System.Data.Linq.ConflictMode.ContinueOnConflict)
        Catch ex As System.Data.Linq.ChangeConflictException
            For Each occ As System.Data.Linq.ObjectChangeConflict In dbTV.ChangeConflicts
                occ.Resolve(System.Data.Linq.RefreshMode.KeepChanges)
            Next
            dbTV.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict)
        End Try
    End Sub

    ''' <summary>
    ''' Kết nối cơ sở dữ liệu. 
    ''' Tham số ConnectionString là biến toàn cục phải được thiết lập giá trị lúc FormMain Load lên
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ConnectToDB() As Boolean
        Try
            dbTV = New DataMainDataContext(ConnectionString)
            vKetNoiThanhCong = True
            Return dbTV.DatabaseExists()
        Catch ex As Exception
            Return False
        End Try
    End Function

    ''' <summary>
    ''' Load du lieu tren bang phim tat dua len List
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Load_DMPhimTat()
        vlstPhimTat = (From ds In dbTV.SYS_PhimTats Where ds.InUsed Select New clsPhimTat(ds.ID, ds.TenNgan, ds.MaNut, ds.TenNut, ds.DienGiai, ds.KeyCode, ds.KeyFn, ds.Nhom)).ToList
    End Sub
    Public Sub Load_ThoiGianLamViec()
        If vIntKTNam = 0 Then
            vIntKTNam = dbTV.GetDateTimeServer.Value.Year
        End If
        If vIntKTThang = 0 Then
            vIntKTThang = dbTV.GetDateTimeServer.Value.Month
        End If
    End Sub
    Public Function GetLabelNgayThangNamInBaoCao(Optional ByVal NgayThangNamBaoCao = 0) As String
        Dim dteNgay As DateTime = dbTV.GetDateTimeServer
        Select Case NgayThangNamBaoCao
            Case "1"
                Return String.Format("{0}, Ngày {1:dd} tháng {2:MM} năm {3:yyyy}", "", dteNgay, dteNgay, dteNgay)
            Case "0"
                Return String.Format("{0}, Ngày {1:dd} tháng {2:MM} năm {3:yyyy}", "", Now, Now, Now)
        End Select
        Return ""
    End Function

    Public Function GetLabelNgayInHienTai(Optional ByVal NgayThangNamBaoCao = 0) As String
        Select Case NgayThangNamBaoCao
            Case "1"
                Return String.Format("Ngày {0:dd/MM/yyyy}", dbTV.GetDateTimeServer.Value)
            Case "0"
                Return String.Format("Ngày {0:dd/MM/yyyy}", DateTime.Now)
        End Select
        Return ""
    End Function

    Public Function GetLabelGioInHienTai(Optional ByVal NgayThangNamBaoCao = 0) As String
        Dim sTMP As String = ""
        Select Case NgayThangNamBaoCao
            Case "1"
                sTMP = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:T}", dbTV.GetDateTimeServer.Value)
            Case "0"
                sTMP = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:T}", DateTime.Now)
        End Select
        Dim lst = sTMP.Split(":").ToList
        Return String.Format("Báo cáo được in vào lúc : {0} giờ {1} phút", lst(0), lst(1))
    End Function

    ''' <summary>
    ''' Formats the font table detail.
    ''' </summary>
    ''' <param name="table">The table.</param>
    Public Sub FormatFontTableDetail(ByRef table As DevExpress.XtraReports.UI.XRTable, Optional ByVal sizeFont As Single = 10.0!)
        Dim _fontChu = New System.Drawing.Font("Arial", sizeFont - 1)
        Dim _fontSo = New System.Drawing.Font("Arial Narrow", sizeFont)
        For Each row As DevExpress.XtraReports.UI.XRTableRow In table.Rows
            For Each _cell As DevExpress.XtraReports.UI.XRTableCell In row.Cells
                If _cell.DataBindings.Count > 0 AndAlso _cell.DataBindings.Item(0).FormatString.Contains("#") Then
                    _cell.Font = _fontSo
                Else
                    _cell.Font = _fontChu
                End If
            Next
        Next
    End Sub

    ''' <summary>
    ''' Formats the font table group or report.
    ''' </summary>
    ''' <param name="table">The table.</param>
    Public Sub FormatFontTableGroupOrReport(ByRef table As DevExpress.XtraReports.UI.XRTable, Optional ByVal sizeFont As Single = 10.0!)
        Dim _fontChu = New System.Drawing.Font("Arial", sizeFont, System.Drawing.FontStyle.Bold)
        Dim _fontSo = New System.Drawing.Font("Arial Narrow", sizeFont, System.Drawing.FontStyle.Bold)

        For Each row As DevExpress.XtraReports.UI.XRTableRow In table.Rows
            For Each _cell As DevExpress.XtraReports.UI.XRTableCell In row.Cells
                If _cell.DataBindings.Count > 0 AndAlso _cell.DataBindings.Item(0).FormatString.Contains("#") Or _cell.Summary.FormatString.Contains("#") Then
                    _cell.Font = _fontSo
                Else
                    _cell.Font = _fontChu
                End If
            Next
        Next
    End Sub

    ''' <summary>
    '''  
    ''' Copy value cell tren gridview dua vao Clipboard
    ''' Doi voi column co type la numeric => chuyen text ve so => chuyen so sang text
    ''' </summary>
    ''' <param name="gridView"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SetClipboardValueCellFocusInGrid(ByRef gridView As DevExpress.XtraGrid.Views.Grid.GridView) As Boolean
        Try
            Dim text = gridView.GetFocusedDisplayText()
            If text IsNot Nothing AndAlso text.Trim() <> "" Then
                text = text.Trim()
                If gridView.FocusedColumn IsNot Nothing AndAlso gridView.FocusedColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric Then
                    text = CDec(text.Replace(" ", "")).ToString()
                End If
                Clipboard.SetText(text)
                Return True
            End If
        Catch ex As Exception
        End Try
        '
        Return False
    End Function

    ''' <summary>
    '''  
    ''' Copy value cell tren gridview dua vao Clipboard
    ''' Doi voi column co type la numeric => chuyen text ve so => chuyen so sang text
    ''' </summary>
    ''' <param name="gridView"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SetClipboardValueCellFocusInGrid(ByRef gridView As VmsGridView) As Boolean
        Try
            Dim text = gridView.GetFocusedDisplayText()
            If text IsNot Nothing AndAlso text.Trim() <> "" Then
                text = text.Trim()
                If gridView.FocusedColumn IsNot Nothing AndAlso gridView.FocusedColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric Then
                    text = CDec(text.Replace(" ", "")).ToString()
                End If
                Clipboard.SetText(text)
                Return True
            End If
        Catch ex As Exception
        End Try
        '
        Return False
    End Function

    Public Sub SetFilterConditionMa(ByRef _gridView As DevExpress.XtraGrid.Views.Grid.GridView, ByRef _column As DevExpress.XtraGrid.Columns.GridColumn, ByVal _fieldName As String, Optional ByVal _value As String = "", Optional ByVal _laChon As Boolean = False)
        'Thiết lập điều kiện lọc cho tất cả các cột trên gridview
        _gridView.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Default
        For Each item As DevExpress.XtraGrid.Columns.GridColumn In _gridView.Columns
            If _column.Equals(item) = False Then
                item.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains
            End If
            'Nếu là cột chọn thì không cho phép filter
            If item.FieldName.ToLower = "chon" Then
                item.OptionsFilter.AllowAutoFilter = False
                item.OptionsFilter.AllowFilter = False
            End If
        Next
        'Thiết lập điều kiện lọc lại cho riêng cột mã
        If New clsBienMoiTruong().PH_DM_LocCotMa = DieuKienLocCotMa.StartWith Then
            _column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Default
            If _value <> "" AndAlso _value <> "*" Then
                _gridView.Columns(_fieldName).FilterInfo = New DevExpress.XtraGrid.Columns.ColumnFilterInfo("[" & _fieldName & "] like '" & _value & "%'")
                _gridView.SetRowCellValue(DevExpress.XtraGrid.GridControl.AutoFilterRowHandle, _fieldName, _value)
            End If
        Else
            _column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains
            If _value <> "" AndAlso _value <> "*" Then
                _gridView.Columns(_fieldName).FilterInfo = New DevExpress.XtraGrid.Columns.ColumnFilterInfo("[" & _fieldName & "] like '%" & _value & "%'")
                _gridView.SetRowCellValue(DevExpress.XtraGrid.GridControl.AutoFilterRowHandle, _fieldName, _value)
            End If
        End If
        '
        If _value <> "" AndAlso _value <> "*" Then
            For i = 0 To _gridView.RowCount - 1
                Dim ma = _gridView.GetRowCellValue(i, _column)
                If ma IsNot Nothing AndAlso ma.ToString.StartsWith(_value) Then
                    _gridView.FocusedRowHandle = i
                    Return
                End If
            Next
        End If
        'Nếu không thấy row focus thì Focus cell lọc mã
        If _laChon Then
            _gridView.FocusedColumn = _column
            _gridView.FocusedRowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle
        End If
    End Sub

    Public Sub SetFilterConditionMa(ByRef _gridView As VmsGridView, ByRef _column As DevExpress.XtraGrid.Columns.GridColumn, ByVal _fieldName As String, Optional ByVal _value As String = "", Optional ByVal _laChon As Boolean = False)
        'Thiết lập điều kiện lọc cho tất cả các cột trên gridview
        _gridView.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Default
        For Each item As DevExpress.XtraGrid.Columns.GridColumn In _gridView.Columns
            If _column.Equals(item) = False Then
                item.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains
            End If
            'Nếu là cột chọn thì không cho phép filter
            If item.FieldName.ToLower = "chon" Then
                item.OptionsFilter.AllowAutoFilter = False
                item.OptionsFilter.AllowFilter = False
            End If
        Next
        'Thiết lập điều kiện lọc lại cho riêng cột mã
        If New clsBienMoiTruong().PH_DM_LocCotMa = DieuKienLocCotMa.StartWith Then
            _column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Default
            If _value <> "" AndAlso _value <> "*" Then
                _gridView.Columns(_fieldName).FilterInfo = New DevExpress.XtraGrid.Columns.ColumnFilterInfo("[" & _fieldName & "] like '" & _value & "%'")
            End If
        Else
            _column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains
            If _value <> "" AndAlso _value <> "*" Then
                _gridView.Columns(_fieldName).FilterInfo = New DevExpress.XtraGrid.Columns.ColumnFilterInfo("[" & _fieldName & "] like '%" & _value & "%'")
            End If
        End If
        '
        If _value <> "" AndAlso _value <> "*" Then
            For i = 0 To _gridView.RowCount - 1
                Dim ma = _gridView.GetRowCellValue(i, _column)
                If ma IsNot Nothing AndAlso ma.ToString.StartsWith(_value) Then
                    _gridView.FocusedRowHandle = i
                    Return
                End If
            Next
        End If
        'Nếu không thấy row focus thì Focus cell lọc mã
        If _laChon Then
            _gridView.FocusedColumn = _column
            _gridView.FocusedRowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle
        End If
    End Sub

    Public Sub ShowGridMenuText(ByVal e As DevExpress.XtraGrid.Views.Grid.GridMenuEventArgs)
        Try
            If e.HitInfo.InColumn Or e.HitInfo.InColumnPanel Then
                e.Menu.Items(0).Caption = "Sắp xếp tăng"
                e.Menu.Items(1).Caption = "Sắp xếp giảm"
                e.Menu.Items(2).Caption = "Hủy sắp xếp"
                e.Menu.Items(3).Caption = "Nhóm cột này"
                e.Menu.Items(4).Caption = "Hiện hộp nhóm"
                e.Menu.Items(5).Caption = "Ẩn cột"
                e.Menu.Items(6).Caption = "Chọn cột"
                e.Menu.Items(7).Caption = "Căn vừa độ rộng"
                e.Menu.Items(8).Caption = "Căn vừa độ rộng tất cả các cột"
                e.Menu.Items(9).Caption = "Lọc dữ liệu"

                If e.Menu.Items.Count > 10 Then e.Menu.Items(10).Caption = "Lập công thức"

            ElseIf e.HitInfo.InGroupColumn Or e.HitInfo.InGroupPanel Then
                e.Menu.Items(0).Caption = "Mở các nhóm"
                e.Menu.Items(1).Caption = "Đóng các nhóm"
                e.Menu.Items(2).Caption = "Sắp xếp tăng"
                e.Menu.Items(3).Caption = "Sắp xếp giảm"
                e.Menu.Items(4).Caption = "Hủy sắp xếp"
                e.Menu.Items(5).Caption = "Hủy nhóm"
                e.Menu.Items(6).Caption = "Ẩn hộp nhóm"
                e.Menu.Items(7).Caption = "Ẩn cột"
                e.Menu.Items(8).Caption = "Chọn cột"
                e.Menu.Items(9).Caption = "Căn vừa độ rộng tất cả các cột"
                e.Menu.Items(10).Caption = "Lọc dữ liệu"

                If e.Menu.Items.Count > 11 Then e.Menu.Items(11).Caption = "Lập công thức"
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' lay thong tin bien moi truong(Co truyen so lieu)
    ''' </summary>
    ''' <param name="TenCauHinh"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetBienMoiTruong(ByVal TenCauHinh As String) As DM_BienMoiTruong
        '//If vlstBienMoiTruong Is Nothing Then Return Nothing
        Return (From ds In dbTV.DM_BienMoiTruongs Where ds.TenCauHinh = TenCauHinh Select ds).FirstOrDefault
    End Function


#Region "Xuất dữ liệu"


    Public Sub ExportExcel(ByVal vGridctrl As DevExpress.XtraGrid.GridControl)
        Dim filename As String = Guid.NewGuid().ToString & ".xls"
        vGridctrl.ExportToXls(System.IO.Path.GetTempPath & "\" & filename)
        Process.Start(System.IO.Path.GetTempPath & "\" & filename)
    End Sub

    ''' <summary>
    ''' Thủ tục kết xuất dữ liệu ra các ứng dụng bên ngoài
    ''' </summary>
    ''' <param name="SaveFileDialog">Hộp thoại hiển thị lưu đường dẫn và tên tệp tin </param>
    ''' <param name="vGridCtrl">Xuất dữ liệu từ một lưới cụ thể</param>
    ''' <param name="ext">Phần mở rộng định dạng tập tin cần xuất, mặc định là xls</param>
    ''' <remarks></remarks>
    Public Sub Export_Dialog(ByVal SaveFileDialog As System.Windows.Forms.SaveFileDialog, ByVal vGridCtrl As DevExpress.XtraGrid.GridControl, Optional ByVal ext As String = "xls")
        Dim vFilePath As String = System.IO.Path.GetTempPath & "\" & Now.ToString("ddMMyyyy_hhmmss") & ".xls"
        'SaveFileDialog.Reset()
        'SaveFileDialog.Title = "Xuất dữ liệu"
        'SaveFileDialog.Filter = "Excel file(*.xls)|*.xls|Pdf files (*.pdf)|*.pdf|Html files (*.html)|*.html|Text files (*.txt)|*.txt"
        'SaveFileDialog.ShowDialog()
        'vFilePath = SaveFileDialog.FileName
        '  Ẩn cột chọn đi để export nó ko ra cột này. Tí export xong thì hiển thị lên[Giữ nguyên trạng thái của grid]
        Dim isChon As Boolean = False
        Dim _VisibleIndex As Integer = 0
        For Each item As DevExpress.XtraGrid.Columns.GridColumn In CType(vGridCtrl.Views(0), ColumnView).Columns
            If item.FieldName.ToLower = "chon" Then
                _VisibleIndex = item.VisibleIndex
                isChon = item.Visible
                item.Visible = False
                Exit For
            End If
        Next
        '
        If vFilePath <> "" Then
            ext = vFilePath.Substring(vFilePath.IndexOf(".") + 1)
            Try
                Select Case ext
                    Case "xls"
                        If Not SaveFileDialog.CheckFileExists Then
                            vGridCtrl.ExportToXls(vFilePath)
                        ElseIf SaveFileDialog.OverwritePrompt Then
                            vGridCtrl.ExportToXls(vFilePath)
                        End If
                    Case "pdf"
                        If Not SaveFileDialog.CheckFileExists Then
                            vGridCtrl.ExportToPdf(vFilePath)
                        ElseIf SaveFileDialog.OverwritePrompt Then
                            vGridCtrl.ExportToPdf(vFilePath)
                        End If
                    Case "html"
                        If Not SaveFileDialog.CheckFileExists Then
                            vGridCtrl.ExportToHtml(vFilePath)
                        ElseIf SaveFileDialog.OverwritePrompt Then
                            vGridCtrl.ExportToHtml(vFilePath)
                        End If
                    Case "txt"
                        If Not SaveFileDialog.CheckFileExists Then
                            vGridCtrl.ExportToText(vFilePath)
                        ElseIf SaveFileDialog.OverwritePrompt Then
                            vGridCtrl.ExportToText(vFilePath)
                        End If
                End Select
            Catch ex As Exception
                vMsg.Show("Lỗi trong quá trình xuất dữ liệu: " & ex.ToString())
            End Try
        End If
        ' Hiển thị cột chọn đi để export nó ko ra cột này
        'Vì ẩn ở trên và grid nó là tham chiếu mặc dù để ByVal. Thế nên mới phải làm cái này 8-x
        If isChon Then
            For Each item As DevExpress.XtraGrid.Columns.GridColumn In CType(vGridCtrl.Views(0), ColumnView).Columns
                If item.FieldName.ToLower = "chon" Then
                    item.Visible = True
                    item.VisibleIndex = _VisibleIndex
                    Exit For
                End If
            Next
        End If
        'Mở file vừa export
        If File.Exists(vFilePath) Then
            Process.Start(vFilePath)
            'If MsgAskDelete(GetTextFromResx("MsgHoiMoFileExport", "Bạn có muốn mở file vừa xuất dữ liệu không?")) = vMsg.vReSult.Yes Then
            '    Process.Start(vFilePath)
            'End If
        End If
    End Sub

    Public Sub Export_Dialog(ByVal vSaveFileDialog As System.Windows.Forms.SaveFileDialog, ByVal vTreeList As DevExpress.XtraTreeList.TreeList, Optional ByVal ext As String = "xls")
        Dim vFilePath As String = ""
        vSaveFileDialog.Reset()
        vSaveFileDialog.Title = "Xuất dữ liệu ra"
        vSaveFileDialog.Filter = "Excel file(*.xls)|*.xls|Pdf files (*.pdf)|*.pdf|Html files (*.html)|*.html|Text files (*.txt)|*.txt"
        vSaveFileDialog.ShowDialog()
        vFilePath = vSaveFileDialog.FileName
        If vFilePath <> "" Then
            Dim iTemp As TreeListViewState = New TreeListViewState(vTreeList)
            iTemp.SaveState()
            vTreeList.ExpandAll()
            ext = vFilePath.Substring(vFilePath.LastIndexOf(".") + 1)
            Try
                Select Case ext
                    Case "xls"
                        If Not vSaveFileDialog.CheckFileExists Then
                            vTreeList.ExportToXls(vFilePath)
                        ElseIf vSaveFileDialog.OverwritePrompt Then
                            vTreeList.ExportToXls(vFilePath)
                        End If
                    Case "pdf"
                        If Not vSaveFileDialog.CheckFileExists Then
                            vTreeList.ExportToPdf(vFilePath)
                        ElseIf vSaveFileDialog.OverwritePrompt Then
                            vTreeList.ExportToPdf(vFilePath)
                        End If
                    Case "html"
                        If Not vSaveFileDialog.CheckFileExists Then
                            vTreeList.ExportToHtml(vFilePath)
                        ElseIf vSaveFileDialog.OverwritePrompt Then
                            vTreeList.ExportToHtml(vFilePath)
                        End If
                    Case "txt"
                        If Not vSaveFileDialog.CheckFileExists Then
                            vTreeList.ExportToText(vFilePath)
                        ElseIf vSaveFileDialog.OverwritePrompt Then
                            vTreeList.ExportToText(vFilePath)
                        End If
                End Select
            Catch ex As Exception
                vMsg.Show(ex.ToString)
            End Try
            iTemp.LoadState()
        End If
    End Sub

    ''' <summary>
    ''' Thủ tục kết xuất dữ liệu ra các ứng dụng bên ngoài
    ''' </summary>
    ''' <param name="SaveFileDialog">Hộp thoại hiển thị lưu đường dẫn và tên tệp tin </param>
    ''' <param name="vXtrRp">Xuất dữ liệu từ một Report cụ thể</param>
    ''' <param name="ext">Phần mở rộng định dạng tập tin cần xuất, mặc định là xls</param>
    ''' <remarks></remarks>
    Public Sub Export_Dialog(ByVal SaveFileDialog As System.Windows.Forms.SaveFileDialog, ByVal vXtrRp As DevExpress.XtraReports.UI.XtraReport, Optional ByVal ext As String = "xls")
        Dim vFilePath As String = ""
        SaveFileDialog.Reset()
        SaveFileDialog.Title = "Xuất dữ liệu"
        SaveFileDialog.Filter = "Excel file(*.xls)|*.xls|Pdf files (*.pdf)|*.pdf|Html files (*.html)|*.html|Text files (*.txt)|*.txt"
        SaveFileDialog.ShowDialog()
        vFilePath = SaveFileDialog.FileName
        If vFilePath <> "" Then
            ext = vFilePath.Substring(vFilePath.IndexOf(".") + 1)
            Try
                Select Case ext
                    Case "xls"
                        If Not SaveFileDialog.CheckFileExists Then
                            vXtrRp.ExportToXls(vFilePath)
                        ElseIf SaveFileDialog.OverwritePrompt Then
                            vXtrRp.ExportToXls(vFilePath)
                        End If
                    Case "pdf"
                        If Not SaveFileDialog.CheckFileExists Then
                            vXtrRp.ExportToPdf(vFilePath)
                        ElseIf SaveFileDialog.OverwritePrompt Then
                            vXtrRp.ExportToPdf(vFilePath)
                        End If
                    Case "html"
                        If Not SaveFileDialog.CheckFileExists Then
                            vXtrRp.ExportToHtml(vFilePath)
                        ElseIf SaveFileDialog.OverwritePrompt Then
                            vXtrRp.ExportToHtml(vFilePath)
                        End If
                    Case "txt"
                        If Not SaveFileDialog.CheckFileExists Then
                            vXtrRp.ExportToText(vFilePath)
                        ElseIf SaveFileDialog.OverwritePrompt Then
                            vXtrRp.ExportToText(vFilePath)
                        End If
                End Select
            Catch ex As Exception
                MsgBox("Lỗi trong quá trình xuất dữ liệu: " & ex.ToString())
            End Try
        End If
    End Sub
    '''' <summary>
    '''' @ThinhPr: Comment
    '''' Phục vụ việc xuất dữ liệu từ TreeList ra các định dạng .xls .pdf .html .txt
    '''' </summary>
    '''' <param name="vSaveFileDialog"></param>
    '''' <param name="vTreeList"></param>
    '''' <param name="ext"></param>
    '''' <remarks></remarks>
    'Public Sub Export_Dialog(ByVal vSaveFileDialog As System.Windows.Forms.SaveFileDialog, ByVal vTreeList As DevExpress.XtraTreeList.TreeList, Optional ByVal ext As String = "xls")
    '    Dim vFilePath As String = ""
    '    vSaveFileDialog.Reset()
    '    vSaveFileDialog.Title = "Xuất dữ liệu ra"
    '    vSaveFileDialog.Filter = "Excel file(*.xls)|*.xls|Pdf files (*.pdf)|*.pdf|Html files (*.html)|*.html|Text files (*.txt)|*.txt"
    '    vSaveFileDialog.ShowDialog()
    '    vFilePath = vSaveFileDialog.FileName
    '    If vFilePath <> "" Then
    '        Dim iTemp As TreeListViewState = New TreeListViewState(vTreeList)
    '        iTemp.SaveState()
    '        vTreeList.ExpandAll()
    '        ext = vFilePath.Substring(vFilePath.IndexOf(".") + 1)
    '        Try
    '            Select Case ext
    '                Case "xls"
    '                    If Not vSaveFileDialog.CheckFileExists Then
    '                        vTreeList.ExportToXls(vFilePath)
    '                    ElseIf vSaveFileDialog.OverwritePrompt Then
    '                        vTreeList.ExportToXls(vFilePath)
    '                    End If
    '                Case "pdf"
    '                    If Not vSaveFileDialog.CheckFileExists Then
    '                        vTreeList.ExportToPdf(vFilePath)
    '                    ElseIf vSaveFileDialog.OverwritePrompt Then
    '                        vTreeList.ExportToPdf(vFilePath)
    '                    End If
    '                Case "html"
    '                    If Not vSaveFileDialog.CheckFileExists Then
    '                        vTreeList.ExportToHtml(vFilePath)
    '                    ElseIf vSaveFileDialog.OverwritePrompt Then
    '                        vTreeList.ExportToHtml(vFilePath)
    '                    End If
    '                Case "txt"
    '                    If Not vSaveFileDialog.CheckFileExists Then
    '                        vTreeList.ExportToText(vFilePath)
    '                    ElseIf vSaveFileDialog.OverwritePrompt Then
    '                        vTreeList.ExportToText(vFilePath)
    '                    End If
    '            End Select
    '        Catch ex As Exception
    '            vMsg.Show(ex.ToString)
    '        End Try
    '        iTemp.LoadState()
    '    End If
    'End Sub
#End Region

    'Public Function GetAll_DMSanPham() As List(Of clsDMSanPham)
    '    Try
    '        Dim dbTmp = New DataMainDataContext(ConnectionString)
    '        Dim lstTmp As New List(Of clsDMSanPham)
    '        lstTmp = (From ds In dbTmp.DM_SanPhams Where ds.InUsed _
    '                  Order By ds.MaSanPham _
    '                  Select New clsDMSanPham With { _
    '                      .ID = ds.ID, .MaSanPham = ds.MaSanPham, .TenSanPham = ds.TenSanPham, _
    '                      .IDNhomSanPham = ds.IDNhomSanPham, .GiaBan = ds.GiaBan.GetValueOrDefault, .GiaNhap = ds.GiaNhap.GetValueOrDefault, _
    '                      .DVT = ds.DVT, .GhiChu = ds.GhiChu, .TinhChatSanPham = ds.TinhChat.GetValueOrDefault, _
    '                      .STT = ds.STT.GetValueOrDefault}).ToList

    '        Dim lstDM_NhomSanPham = (From ds In dbTmp.DM_NhomSanPhams Where ds.InUsed Select ds.ID, ds.MaNhom, ds.TenNhom).ToList
    '        For Each item In From ds In lstTmp Where Not String.IsNullOrEmpty(ds.IDNhomSanPham) Select ds
    '            Dim objNhomSanPham = (From ds In lstDM_NhomSanPham Where ds.ID = item.IDNhomSanPham Select ds).FirstOrDefault
    '            If objNhomSanPham IsNot Nothing Then
    '                item.MaNhomSanPham = objNhomSanPham.MaNhom
    '                item.TenNhomSanPham = objNhomSanPham.TenNhom
    '            End If
    '        Next

    '        Return lstTmp
    '    Catch ex As Exception
    '        MsgErr(ex.Message)
    '        Return New List(Of clsDMSanPham)
    '    End Try
    'End Function

    Public Function GetAll_DMKhachHang() As List(Of clsDMKhachHang)
        Try
            Dim dbTmp = New DataMainDataContext(ConnectionString)
            Dim lstTmp As New List(Of clsDMKhachHang)
            lstTmp = (From ds In dbTmp.DM_KhachHangs Where ds.InUsed _
                      Order By ds.MaKhachHang _
                      Select New clsDMKhachHang With { _
                          .ID = ds.ID, .MaKhachHang = ds.MaKhachHang, .TenKhachHang = ds.TenKhachHang, _
                          .DiaChi = ds.DiaChi, .DienThoai = ds.DienThoai, .MaSoThue = ds.MaSoThue, .GhiChu = ds.GhiChu, _
                          .LH_DiaChi = ds.LH_DiaChi, .LH_DienThoai = ds.LH_DienThoai, .LH_Email = ds.LH_Email, .LH_HoTen = ds.LH_HoTen _
                          }).ToList

            Return lstTmp
        Catch ex As Exception
            MsgErr(ex.Message)
            Return New List(Of clsDMKhachHang)
        End Try
    End Function

    Public Sub UpdateTo_lstSourceAllKhachHang(ByVal ID As String)
        Dim objUpdate = (From ds In lstSourceAllKhachHang Where ds.ID = ID Select ds).FirstOrDefault
        If objUpdate IsNot Nothing Then
            Dim objKhachHang = (From ds In dbTV.DM_KhachHangs Where ds.InUsed AndAlso ds.ID = ID Select ds).FirstOrDefault
            If objKhachHang IsNot Nothing Then
                With objUpdate
                    .MaKhachHang = objKhachHang.MaKhachHang
                    .TenKhachHang = objKhachHang.TenKhachHang
                    .DiaChi = objKhachHang.DiaChi
                    .DienThoai = objKhachHang.DienThoai
                    .MaSoThue = objKhachHang.MaSoThue
                    .GhiChu = objKhachHang.GhiChu
                    .LH_DiaChi = objKhachHang.LH_DiaChi
                    .LH_DienThoai = objKhachHang.LH_DienThoai
                    .LH_Email = objKhachHang.LH_Email
                    .LH_HoTen = objKhachHang.LH_HoTen
                End With
            End If
        End If
    End Sub

    Public Sub InsertTo_lstSourceAllKhachHang(ByVal ID As String)
        Dim objKhachHang = (From ds In dbTV.DM_KhachHangs Where ds.InUsed AndAlso ds.ID = ID Select ds).FirstOrDefault
        If objKhachHang IsNot Nothing Then
            Dim objAdd As New clsDMKhachHang
            With objAdd
                .ID = ID
                .MaKhachHang = objKhachHang.MaKhachHang
                .TenKhachHang = objKhachHang.TenKhachHang
                .DienThoai = objKhachHang.DienThoai
                .DiaChi = objKhachHang.DiaChi
                .MaSoThue = objKhachHang.MaSoThue
                .GhiChu = objKhachHang.GhiChu
                .LH_DiaChi = objKhachHang.LH_DiaChi
                .LH_DienThoai = objKhachHang.LH_DienThoai
                .LH_Email = objKhachHang.LH_Email
                .LH_HoTen = objKhachHang.LH_HoTen
                If (From ds In lstSourceAllKhachHang Where ds.ID = ID Select ds).FirstOrDefault Is Nothing Then lstSourceAllKhachHang.Add(objAdd)
            End With
        End If
    End Sub

    'Public Sub UpdateTo_lstSourceAllSanPham(ByVal ID As String)
    '    Dim objUpdate As clsDMSanPham
    '    objUpdate = (From ds In lstSourceAllSanPham Where ds.ID = ID Select ds).FirstOrDefault
    '    If objUpdate IsNot Nothing Then
    '        Dim objSanPham = (From ds In dbTV.DM_SanPhams Where ds.InUsed AndAlso ds.ID = ID Select ds).FirstOrDefault
    '        If objSanPham IsNot Nothing Then
    '            With objUpdate
    '                .MaSanPham = objSanPham.MaSanPham
    '                .TenSanPham = objSanPham.TenSanPham
    '                .GiaNhap = objSanPham.GiaNhap.GetValueOrDefault
    '                .GiaBan = objSanPham.GiaBan.GetValueOrDefault
    '                .ThueSuat = objSanPham.ThueSuat.GetValueOrDefault
    '                .DVT = objSanPham.DVT
    '                .GhiChu = objSanPham.GhiChu
    '                .STT = objSanPham.STT.GetValueOrDefault
    '                .TinhChatSanPham = objSanPham.TinhChat.GetValueOrDefault
    '                '// Các khóa ngoại
    '                Dim objNhomSanPham = (From ds In dbTV.DM_NhomSanPhams Where ds.ID = objSanPham.IDNhomSanPham Select ds).FirstOrDefault
    '                If objNhomSanPham IsNot Nothing Then
    '                    .MaNhomSanPham = objNhomSanPham.MaNhom
    '                    .TenNhomSanPham = objNhomSanPham.TenNhom
    '                End If
    '                '

    '            End With
    '        End If
    '    End If



    'End Sub

    'Public Sub InsertTo_lstSourceAllSanPham(ByVal ID As String)
    '    Dim objSanPham = (From ds In dbTV.DM_SanPhams Where ds.InUsed AndAlso ds.ID = ID Select ds).FirstOrDefault
    '    If objSanPham IsNot Nothing Then
    '        Dim objAdd As New clsDMSanPham
    '        With objAdd
    '            .ID = ID
    '            .IDNhomSanPham = objSanPham.IDNhomSanPham
    '            .MaSanPham = objSanPham.MaSanPham
    '            .TenSanPham = objSanPham.TenSanPham
    '            .GiaNhap = objSanPham.GiaNhap.GetValueOrDefault
    '            .GiaBan = objSanPham.GiaBan.GetValueOrDefault
    '            .ThueSuat = objSanPham.ThueSuat.GetValueOrDefault
    '            .DVT = objSanPham.DVT
    '            .GhiChu = objSanPham.GhiChu
    '            .STT = objSanPham.STT.GetValueOrDefault
    '            .TinhChatSanPham = objSanPham.TinhChat.GetValueOrDefault
    '            '// Các khóa ngoại
    '            Dim objNhomSanPham = (From ds In dbTV.DM_NhomSanPhams Where ds.ID = objSanPham.IDNhomSanPham Select ds).FirstOrDefault
    '            If objNhomSanPham IsNot Nothing Then
    '                .MaNhomSanPham = objNhomSanPham.MaNhom
    '                .TenNhomSanPham = objNhomSanPham.TenNhom
    '            End If
    '        End With
    '        If (From ds In lstSourceAllSanPham Where ds.ID = ID Select ds).FirstOrDefault Is Nothing Then lstSourceAllSanPham.Add(objAdd)
    '    End If
    'End Sub

    Public Sub SaveLog(ByVal ChucNang As String, ByVal SuKien As String, ByVal NoiDung As String, Optional ByVal ID As String = "", Optional ByVal TenForm As String = "")
        'If vUser.CanBo.UserName.ToLower <> "superadmin" Then
        dbTV.Pro_SaveLog_Insert(ChucNang, SuKien, NoiDung, ID, "", "Cafe", String.Format("{0}({1})", System.Environment.MachineName, GetMACAddress()), "UserName")
        ' End If
    End Sub

    Public Function GetDate(ByVal Year As Integer, ByVal Month As Integer, ByVal Day As Integer)
        Dim dayIsMonth = Date.DaysInMonth(Year, Month)
        'Trường hợp: GetDate(30, 2, 2013) => 28/2/2013
        If Day > dayIsMonth Then
            Return New Date(Year, Month, dayIsMonth)
        Else
            Return New Date(Year, Month, Day)
        End If
    End Function

    ''' <summary>
    ''' Kiem tra obj neu la so am thi return TRUE
    ''' </summary>
    ''' <param name="obj"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function CheckSoAm(ByVal obj As Object)
        Try
            If (obj IsNot Nothing AndAlso obj.ToString.Contains("-")) _
                OrElse (IsNumeric(obj) AndAlso CDec(obj) < 0) Then
                Return True
            End If
            Return False
        Catch ex As Exception
            MsgErr(ex.Message)
            Return False
        End Try
    End Function
    Public Function TienBangChu(ByVal intSoTien As Int64) As String

        If intSoTien < 0 Then
            intSoTien = 0 - intSoTien
        End If
        Dim strSoTien As String = intSoTien.ToString
        Dim arrStrDonVi() As String = {"", "nghìn ", "triệu ", "tỷ ", "nghìn ", "triệu "}
        Dim strSo As String
        Dim strTien As String = ""
        Dim strTemp As String
        Dim intDem As Byte
        If strSoTien.Trim = "" Or strSoTien.Trim = "0" Then
            Return "không đồng."
        End If
        Do While (Not strSoTien.Equals(""))
            If strSoTien.Length <> 0 Then
                strSo = getNum(strSoTien)           'lấy 3 số sau cùng
                strSoTien = Left(strSoTien, strSoTien.Length - strSo.Length)    'Lấy các số còn lại trước 3 số sau cùng
                strTemp = setNum(strSo)
                strSo = strTemp
                If Not strSo.Equals("") Then
                    strTemp = strTemp + arrStrDonVi(intDem)
                    strTien = strTemp + strTien
                End If
                intDem = intDem + 1
            End If
        Loop
        strTemp = UCase(Left(strTien, 1))
        Return strTemp & Right(strTien, Len(strTien) - 1) & "đồng."
    End Function

    Private Function getNum(ByVal strSoTien As String) As String
        Dim strSo As String
        If strSoTien.Length >= 3 Then
            strSo = Right(strSoTien, 3)
        Else
            strSo = Right(strSoTien, strSoTien.Length)
        End If
        Return strSo
    End Function

    Private Function setNum(ByVal strSoTien As String) As String
        Dim strReturn As String = ""
        Dim blnFlag0 As Boolean
        Dim blnFlag1 As Boolean
        Dim strTemp As String

        strTemp = strSoTien
        Dim arrStrKySo() As String = {"không ", "một ", "hai ", "ba ", "bốn ", "năm ", "sáu ", "bảy ", "tám ", "chín "}
        'Xet hang tram
        If strSoTien.Length = 3 Then
            If Not (Left(strSoTien, 1) = 0 And Left(Right(strSoTien, 2), 1) = 0 And Right(strSoTien, 1) = 0) Then
                strReturn = arrStrKySo(Left(strSoTien, 1)) + "trăm "
            End If
            strSoTien = Right(strSoTien, 2)
        End If
        'Xet hang chuc
        If strSoTien.Length = 2 Then
            If Left(strSoTien, 1) = 0 Then
                If Right(strSoTien, 1) <> 0 Then
                    strReturn = strReturn + "linh "
                End If
                blnFlag0 = True
            Else
                If Left(strSoTien, 1) = 1 Then
                    strReturn = strReturn + "mười "
                Else
                    strReturn = strReturn + arrStrKySo(Left(strSoTien, 1)) + "mươi "
                    blnFlag1 = True
                End If
            End If
            strSoTien = Right(strSoTien, 1)
        End If
        'Xet hang don vi
        If Right(strSoTien, 1) <> 0 Then
            If Left(strSoTien, 1) = 5 And Not blnFlag0 Then
                If strTemp.Length = 1 Then
                    strReturn = strReturn + "năm "
                Else
                    strReturn = strReturn + "lăm "
                End If
            Else
                If Left(strSoTien, 1) = 1 And Not (Not blnFlag1 Or blnFlag0) And strReturn <> "" Then
                    strReturn = strReturn + "mốt "
                Else
                    strReturn = strReturn + arrStrKySo(Left(strSoTien, 1)) + ""
                End If
            End If
        Else
        End If
        Return strReturn
    End Function

    Public Function GetPermissions(Optional ByVal intUserID As String = "") As List(Of String)
        Dim arrlstTemp As New List(Of String)
        'duyệt các quyền được phép
        For Each strPermission As String In From ds In dbTV.DM_Quyens _
                                          Join ds1 In dbTV.TG_NguoiDung_Quyens On ds.ID Equals ds1.ID_Quyen _
                                          Where ds1.InUsed AndAlso ds1.ID_NguoiDung.Equals(intUserID) _
                                          Select ds.MaQuyen
            If Not arrlstTemp.Contains(strPermission) Then
                arrlstTemp.Add(strPermission)
            End If
        Next
        If arrlstTemp.Count = 0 Then
            'duyệt những quyền thuộc nhóm cho phép sử dụng
            For Each intGroupID As String In From ds In GetGroups(intUserID)
                Dim intID_Group As String = intGroupID
                For Each strPermission As String In From ds In dbTV.DM_Quyens _
                                                  Join ds1 In dbTV.TG_Quyen_Nhom_NDs On ds.ID Equals ds1.ID_Quyen _
                                                  Where ds1.ID_NhomND.Equals(intID_Group) AndAlso ds1.InUsed _
                                                  Select ds.MaQuyen
                    arrlstTemp.Add(strPermission)
                Next
            Next
        End If
        GetPermissions = (From ds In arrlstTemp Select ds Distinct).ToList
    End Function

    Public Function GetGroups(Optional ByVal intUserID As String = "") As Collections.ArrayList
        Dim arrlstTemp As New Collections.ArrayList
        For Each intGroupID As String In From ds In dbTV.DM_Nhom_NDs _
                                    Join ds1 In dbTV.TG_NguoiDung_Nhom_NDs On ds.ID Equals ds1.ID_NhomND _
                                    Where ds.InUsed AndAlso ds1.InUsed AndAlso ds1.ID_NguoiDung.Equals(intUserID) _
                                    Select ds.ID
            arrlstTemp.Add(intGroupID)
        Next
        GetGroups = arrlstTemp
    End Function

    Public Class common

        Public Shared KeyCode As String = "v6la89"
         
        Public Shared Function Encrypt(ByVal toEncrypt As String, ByVal useHashing As Boolean, ByVal key As String) As String
            Dim keyArray As Byte()
            Dim toEncryptArray As Byte() = UTF8Encoding.UTF8.GetBytes(toEncrypt)

            If useHashing Then
                Dim hashmd5 As New MD5CryptoServiceProvider()
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key))
                hashmd5.Clear()
            Else
                keyArray = UTF8Encoding.UTF8.GetBytes(key)
            End If

            Dim tdes As New TripleDESCryptoServiceProvider()
            tdes.Key = keyArray
            tdes.Mode = CipherMode.ECB
            tdes.Padding = PaddingMode.PKCS7

            Dim cTransform As ICryptoTransform = tdes.CreateEncryptor()
            Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
            tdes.Clear()
            Return Convert.ToBase64String(resultArray, 0, resultArray.Length)
        End Function

        Public Shared Function Decrypt(ByVal todecrypt As String, ByVal key As String, ByVal usehashing As Boolean) As String
            Dim toEncryptArray As Byte()
            Try
                toEncryptArray = Convert.FromBase64String(todecrypt.Replace(" ", "+"))
            Catch generatedExceptionName As Exception
                Return String.Empty
            End Try

            Dim keyArray As Byte()
            If usehashing Then
                Using hashmd5 = New MD5CryptoServiceProvider()
                    keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes(key))
                End Using
            Else
                keyArray = Encoding.UTF8.GetBytes(key)
            End If
            Using tdes = New TripleDESCryptoServiceProvider() With { _
              .Key = keyArray, _
              .Mode = CipherMode.ECB, _
              .Padding = PaddingMode.PKCS7 _
            }
                Using transform = tdes.CreateDecryptor()
                    Try
                        Dim resultArray = transform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
                        Return Encoding.UTF8.GetString(resultArray)
                    Catch generatedExceptionName As Exception
                        Return String.Empty
                    End Try
                End Using
            End Using
        End Function
    End Class

    Public Class KhuDauTiengViet
        Private Shared unichars() As Char = { _
                              "à", "á", "ả", "ã", "ạ", _
                              "ă", "ằ", "ắ", "ẳ", "ẵ", "ặ", _
                              "â", "ầ", "ấ", "ẩ", "ẫ", "ậ", _
                              "đ", "è", "é", "ẻ", "ẽ", "ẹ", _
                              "ê", "ề", "ế", "ể", "ễ", "ệ", _
                              "ì", "í", "ỉ", "ĩ", "ị", _
                              "ò", "ó", "ỏ", "õ", "ọ", _
                              "ô", "ồ", "ố", "ổ", "ỗ", "ộ", _
                              "ơ", "ờ", "ớ", "ở", "ỡ", "ợ", _
                              "ù", "ú", "ủ", "ũ", "ụ", _
                              "ư", "ừ", "ứ", "ử", "ữ", "ự", _
                              "ỳ", "ý", "ỷ", "ỹ", "ỵ", _
                              "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư"}

        Public Shared Function ToKhongDau(ByVal i As String) As String
            Dim index As Integer = -1
            For Each k In unichars
                If k = i Then
                    index = Array.IndexOf(unichars, k)
                    Exit For
                End If
            Next
            If index >= 0 AndAlso index <= 16 Then
                Return "a"
            ElseIf index = 17 Then
                Return "d"
            ElseIf index > 16 AndAlso index <= 28 Then
                Return "e"
            ElseIf index > 28 AndAlso index <= 33 Then
                Return "i"
            ElseIf index > 33 AndAlso index <= 50 Then
                Return "o"
            ElseIf index > 50 AndAlso index <= 61 Then
                Return "u"
            ElseIf index > 61 AndAlso index <= 66 Then
                Return "y"
            ElseIf index > 66 AndAlso index <= 68 Then
                Return "A"
            ElseIf index = 69 Then
                Return "D"
            ElseIf index = 70 Then
                Return "E"
            ElseIf index = 71 OrElse index = 72 Then
                Return "O"
            ElseIf index = 73 Then
                Return "U"
            End If

            Return i
        End Function

        Public Shared Function ConvertToKhongDau(ByVal str As String) As String
            Dim kq As String = ""
            For Each i In str.ToCharArray
                kq &= ToKhongDau(i.ToString)
            Next
            Return kq
        End Function
    End Class

End Module
